from typing import Any
from django.db import models
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.models import CoreModel
from dvadmin.utils.viewset import CustomModelViewSet
from rest_framework import serializers
from .station import Station
from django.conf import settings
import os

# drf专用过滤器模块
from django_filters import rest_framework as filters
from station_system.utils.image_process import img_proccess_save,img_proccess_delete



class Jiajutiaozhengtaizhang(CoreModel):
    station = models.TextField(verbose_name='station', blank=True, null=True)
    NO = models.TextField(verbose_name='NO', blank=True, null=True)
    quyu = models.TextField(verbose_name='区域', blank=True, null=True)
    tiaozhengneirong = models.TextField(verbose_name='调整内容', blank=True, null=True)
    tiaozhengduandian = models.TextField(verbose_name='调整断点', blank=True, null=True)
    shifoufuyuan = models.TextField(verbose_name='是否复原', blank=True, null=True)
    tiaozhengriqi = models.TextField(verbose_name='调整日期', blank=True, null=True)
    jilubianhao = models.TextField(verbose_name='记录编号', blank=True, null=True)
    beizhu = models.TextField(verbose_name='备注', blank=True, null=True)

    class Meta:
        db_table="station_jiajutiaozhengtaizhang"



class JiajutiaozhengtaizhangFilter(filters.FilterSet):
    station = filters.CharFilter(field_name='station', lookup_expr='icontains')
    quyu = filters.CharFilter(field_name='quyu', lookup_expr='icontains')

    class Meta:
        models = Jiajutiaozhengtaizhang
        fields = '__all__'



class  JiajutiaozhengtaizhangImage(models.Model):
    file_path = models.ImageField(upload_to='images/jiajutiaozhengtaizhang/', verbose_name='图片路径', blank=True, null=True)
    file_name = models.TextField(verbose_name='图片名称', blank=True, null=True)
    jiajutiaozhengtaizhang = models.ForeignKey(Jiajutiaozhengtaizhang, on_delete=models.CASCADE, verbose_name='jiajutiaozhengtaizhang',related_name='images', blank=True, null=True)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    class Meta:
        db_table="station_jiajutiaozhengtaizhang_image"
    


from rest_framework import serializers 
class JiajutiaozhengtaizhangImageModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = JiajutiaozhengtaizhangImage
        fields = '__all__'


class JiajutiaozhengtaizhangModelSerializer(CustomModelSerializer):    
    station_name = serializers.SerializerMethodField(read_only=True)
    images = JiajutiaozhengtaizhangImageModelSerializer(many=True, read_only=True)

    def get_station_name(self, obj):
        try:
            # st = Station.objects.filter(code=obj.station)[0]
            st = Station.objects.get(code=obj.station)
            if st:
                return str(st.name)
            else:
                return 'None'
        except:
            return 'lookup  error! '

    class Meta:
        model = Jiajutiaozhengtaizhang
        fields = '__all__'


class JiajutiaozhengtaizhangViewSet(CustomModelViewSet):
    permission_classes = []
    values_queryset = Jiajutiaozhengtaizhang.objects.all().order_by('station')
    serializer_class = JiajutiaozhengtaizhangModelSerializer
    filter_class = JiajutiaozhengtaizhangFilter


from rest_framework.viewsets import ModelViewSet
class JiajutiaozhengtaizhangImageViewSet(ModelViewSet):
    permission_classes = []
    queryset = JiajutiaozhengtaizhangImage.objects.all()
    serializer_class = JiajutiaozhengtaizhangImageModelSerializer

    def perform_create(self, serializer):
        # return super().perform_create(serializer)
        # image是前端传过来的图片，file_path是前端传过来的文件夹名
        image = serializer.validated_data['file_path']

        print(self.request.data)

        # print('serializer.validated_data', serializer.validated_data)

        # file是保存进入的文件夹，计划为station，file_name是前端传过来的文件夹名，通过row可以找到对应的station
        file = self.request.data.get('station')
        # 取出来的id是字符串，需要转换成int
        try:
            # 如果int转换出错，就是None
            jiajutiaozhengtaizhang_id = int(self.request.data.get('jiajutiaozhengtaizhang_id'))
             
        except:
            jiajutiaozhengtaizhang_id = None

        print('serializer.validated_data', serializer.validated_data)
        print(image, file, jiajutiaozhengtaizhang_id)
        img_name, img_backend_relative_path = img_proccess_save(image, file, imageModel=serializer.Meta.model)

        jiajutiaozhengtaizhang = Jiajutiaozhengtaizhang.objects.get(id=jiajutiaozhengtaizhang_id)

        print(jiajutiaozhengtaizhang, img_name, img_backend_relative_path)

        serializer.save(file_path=img_backend_relative_path, jiajutiaozhengtaizhang=jiajutiaozhengtaizhang, file_name=img_name)

    def perform_destroy(self, instance):
        # return super().perform_destroy(instance)
        # print('instance', instance)
        img_proccess_delete(self, instance)
        instance.delete()


